package com.example.demo.config;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.MqttMessage;

public class MqttClientON {
    public static void clientON(String msg, String topic,MqttClient client) {
        try {

            // 创建消息
            MqttMessage mqttMessage = new MqttMessage(msg.getBytes());
            // 设置消息服务质量
            mqttMessage.setQos(2);
            // 发布消息
            client.publish(topic, mqttMessage);
            // 断开连接
//            client.disconnect();
            // 关闭客户端
//            client.close();
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
    }

    public static MqttClient createClient() {
        MqttClient client = null;
        try {
            client = new MqttClient("tcp://172.18.100.27:30767", "mqtt2Kafka");
            // 创建链接参数
            MqttConnectOptions connOpts = new MqttConnectOptions();
            // 在重新启动和重新连接时记住状态
            connOpts.setCleanSession(false);
            // 建立连接
            client.connect(connOpts);
        } catch (MqttException e) {
            throw new RuntimeException(e);
        }
        return client;
    }
}
